package com.bjpowernode.springboot.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.net.URL;
import java.util.UUID;

/**
 * Http工具类
 */
@SuppressWarnings("all")
public class HttpUtils {
    // 定义HttpClient连接池对象
    private PoolingHttpClientConnectionManager connectionManager;

    public HttpUtils() {
        // 创建连接池对象
        this.connectionManager = new PoolingHttpClientConnectionManager();
        // 设置相关的连接参数
        this.connectionManager.setMaxTotal(100); // 最大连接池数量
        this.connectionManager.setDefaultMaxPerRoute(10); // 当前主机的连接池数量
    }

    /**
     * 获取指定url地址的html页面的所有内容
     * @param url
     * @return
     */
    public String getHtml(String url) {
        // 从连接池冲获取HttpClient对象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(this.connectionManager).build();

        // 创建HttpGet对象  实现Get请求
        HttpGet httpGet = new HttpGet(url); // 设置请求路径

        // 设置http相关参数
        httpGet.setConfig(this.getConfig());

        // 创建响应对象
        CloseableHttpResponse response = null;

        try {
            // 获取响应对象
            response = httpClient.execute(httpGet);

            // 判断当前响应是否成功
            if (response.getStatusLine().getStatusCode() == 200) {
                // 如果当前的状态码为200，表明响应成功，获取内容
                String content = EntityUtils.toString(response.getEntity(), "utf8");

                return content; // 返回
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            if (response != null) { // 防止空指针异常，先做空判断
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            // 由于使用池化技术，所以我们不需要手动释放HttpClient对象的资源，完全交由连接池来管理
        }
        return ""; // 如果没有成功直接放回空字符串
    }

    //获取url 返回字符串 解决中文乱码问题
    public String Gget(String url1) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String context = "";
        try {
            URL url = new URL(url1);
            URI uri = new URI(url.getProtocol(), url.getHost() + ":" + url.getPort(), url.getPath(), url.getQuery(), null);
            // 创建httpget.
            HttpGet httpget = new HttpGet(uri);
            // System.out.println("executing request " + httpget.getURI());
            // 执行get请求.
            CloseableHttpResponse response = httpclient.execute(httpget);
            // 获取响应实体
            HttpEntity entity = response.getEntity();
            // System.out.println("--------------------------------------");
            // 打印响应状态
            System.out.println(response.getStatusLine());
            if (entity != null) {
                // 打印响应内容 ，转换为utf-8格式，避免所传内容包含汉字乱码
                context = EntityUtils.toString(entity, "UTF-8");
                // System.out.println(context);
            }
            response.close();
            return context;
        } catch (Exception e) {
            e.printStackTrace();
            return "Exception";
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 设置http的相关设置，返回RequestConfig对象，将其作为参数设置给HttpGet对象
     * @return
     */
    public RequestConfig getConfig() {
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(1000) // 设置连接超时
                .setConnectionRequestTimeout(500) // 设置连接请求超时
                .setSocketTimeout(10000).build(); // 设置套接字超时
        return config;
    }
}
